package com.itzg.filestats;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ResultsFrame extends JFrame {
	private static final long serialVersionUID = 1L;

	private static final Logger logger = LoggerFactory
			.getLogger(ResultsFrame.class);

	private final Analyzer analyzer;

	public ResultsFrame(Analyzer analyzer) {
		this.analyzer = analyzer;
		initComponents();
	}

	protected void initComponents() {
		JPanel buttonPnl = new JPanel();
		buttonPnl.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
		JButton saveBtn = new JButton("Save scenario");
		saveBtn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				saveScenario();
			}
		});
		buttonPnl.add(saveBtn);
		
		JPanel parts = new JPanel();
		Font defaultFont = parts.getFont();
		Font boldFont = defaultFont.deriveFont(Font.BOLD);
		Font plainFont = defaultFont.deriveFont(Font.PLAIN);
		parts.setLayout(new BoxLayout(parts, BoxLayout.PAGE_AXIS));
		String[] lines = analyzer.toString().split("\n");
		for (String line : lines) {
			final JLabel lineLbl = new JLabel(line);
			if (line.startsWith("=")) {
				lineLbl.setBorder(new EmptyBorder(10, 0, 0, 0));
				lineLbl.setFont(boldFont);
			}
			else {
				lineLbl.setFont(plainFont);
			}
			parts.add(lineLbl);
		}
		
		JPanel contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(10, 10, 10, 10));
		contentPane.setLayout(new BorderLayout(10, 10));
		contentPane.add(parts, BorderLayout.CENTER);
		contentPane.add(buttonPnl, BorderLayout.SOUTH);
		
		setContentPane(contentPane);
	}

	protected void saveScenario() {
		SaveScenarioDlg dlg = new SaveScenarioDlg(analyzer);
		dlg.setVisible(true);
		dlg.getScenarioName();
		
		if (dlg.isSaved()) {
			logger.info("Saving scenario {} to file {}", dlg.getScenarioName(), dlg.getScenarioFileToSave());
			analyzer.saveToScenarioFile(dlg.getScenarioName(),  dlg.getScenarioFileToSave());
		}
	}

}
